package cn.wolfcode.cloud.shop.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    public static final String TOKEN_IN_COOKIE_DOMAIN = "localhost";

    public static final String TOKEN_IN_COOKIE_PATH = "/";

    public static final String TOKEN_IN_COOKIE_NAME = "userToken";

    public static final int EXPIRE_TIME = 1800;

    public static void addCookie(HttpServletResponse resp,String cookieName,String cookieValue){
        Cookie cookie = new Cookie(cookieName,cookieValue);
        cookie.setDomain(TOKEN_IN_COOKIE_DOMAIN);
        cookie.setPath(TOKEN_IN_COOKIE_PATH);
        cookie.setMaxAge(EXPIRE_TIME);
        resp.addCookie(cookie);
    }

    public static Cookie getCookie(HttpServletRequest request, String cookieName) {

        Cookie[] cookies = request.getCookies();
        if(cookies == null){
            return null;
        }
        for (Cookie cookie : cookies) {
            if(cookieName.equals(cookie.getName())){
                return cookie;
            }
        }
        return null;
    }
}
